package com.xlh.virtualization.websocket;

import com.google.gson.Gson;
import com.xlh.enums.user.RoleEnum;
import com.xlh.param.course.TheoryLeanTimeStatisticsParam;
import com.xlh.service.courseTest.TheoryService;
import com.xlh.util.SpringContextUtil;
import com.xlh.websocket.GetHttpSessionConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chufangzheng
 * 统计理论课学习时长统计websocket
 */

@ServerEndpoint(value = "/ws/theory/course/learntime/{chapterId}", configurator = GetHttpSessionConfigurator.class)
@Component
@Slf4j
public class CourseTheoryLearnTimeWebsocket {


    /**
     * 理论课多步骤实验
     */
    private static final TheoryService theoryService = SpringContextUtil.getBean(TheoryService.class);

    /**
     * 存储对象
     */
    private ConcurrentHashMap<Long, TheoryLeanTimeStatisticsParam> store = new ConcurrentHashMap();

    /**
     * 进入时间
     */
    private Long enterTime;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 当前用户是否是学生
     */
    private Boolean isStudent;

    /**
     * websocket 链接
     */
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("chapterId") Long chapterId, EndpointConfig config) {
        this.session = session;
        this.userId = (Long) config.getUserProperties().get("userId");
        this.isStudent = Objects.equals(RoleEnum.STUDENT.getRoleCode(), config.getUserProperties().get("roleId"));

    }

    @OnMessage
    public void onMessage( String jsonStr, Session session) {

        if(!isStudent) return;
        Gson gson=new Gson();
        TheoryLeanTimeStatisticsParam theoryLeanTimeStatisticsParam = gson.fromJson(jsonStr, TheoryLeanTimeStatisticsParam.class);
        theoryLeanTimeStatisticsParam.setUserId(userId);
        Long enterTime =  System.currentTimeMillis();
        this.enterTime = enterTime;
        store.put( enterTime, theoryLeanTimeStatisticsParam );
    }

    @OnClose
    public void onClose() {

        if(!isStudent) return;
        synchronized (CourseTheoryLearnTimeWebsocket.class) {
            // 获取存入MAP的key   获取存入MAP的value
            TheoryLeanTimeStatisticsParam theoryLeanTimeStatisticsParam = store.get( enterTime );
            if(Objects.isNull(theoryLeanTimeStatisticsParam)){
                return;
            }
            boolean isLegal = checkParam(theoryLeanTimeStatisticsParam);
            if(isLegal){
                Long closeTime = System.currentTimeMillis();
                Long learnTime = closeTime - enterTime;
                theoryLeanTimeStatisticsParam.setLearnTime(learnTime/1000);
                theoryService.theoryLearnTime(theoryLeanTimeStatisticsParam);
            }
        }
    }

    /**
     * 检查传递过来的参数是否合法
     * @param theoryLeanTimeStatisticsParam
     * @return
     */
    private boolean checkParam(TheoryLeanTimeStatisticsParam theoryLeanTimeStatisticsParam) {

        if(Objects.isNull(theoryLeanTimeStatisticsParam.getUserId())){
             return false;
        }
        if(Objects.isNull(theoryLeanTimeStatisticsParam.getCourseId())){
            return false;
        }
        if(Objects.isNull(theoryLeanTimeStatisticsParam.getChapterId())){
            return false;
        }
        if(Objects.isNull(theoryLeanTimeStatisticsParam.getClassId())){
            return false;
        }
        return true;
    }


}
